package tetris.data;

import java.math.BigInteger;

public class Board
{
    int[][] board = new int[10][20];
    
    public Board(String theBoard)
    {
        String brd = new BigInteger(theBoard, 16).toString(2);
        for (int i = 0; i < brd.length(); i++)
        {
            board[i%10][i/10] = brd.charAt(i) - 48;
        }
    }
    
    private Board(int[][] theBoard)
    {
        this.board = theBoard;
    }
    
    public void execute(Piece piece)
    {
        blit(piece);
        removeRows();
    }
    
    private void removeRows()
    {
        for (int i = board.length-1; i >= 0; i--)
        {
            if (rowFull(i))
            {
                collapseRow(i);
                i++;
            }
        }
    }
    
    private void collapseRow(int i)
    {
        for (; i >= 0; i--)
        {
            for (int j = 0; j < board[0].length; j++)
            {
                if (i == 0)
                {
                    board[i][j] = 0;
                }
                else
                {
                    board[i][j] = board[i-1][j];
                }
            }
        }
    }
    
    private boolean rowFull(int i)
    {
        boolean result = true;
        
        for (int j = 0; j < board[0].length; j++)
        {
            if (board[i][j] == 0)
            {
                result = false;
                break;
            }
        }
        
        return result;
    }
    
    private void blit(Piece piece)
    {
        for (int i = 0; i < piece.piece.length; i++)
        {
            for (int j = 0; j < piece.piece[0].length; j++)
            {
                board[piece.row + (i - 2)][piece.col + (j - 2)] |= piece.piece[i][j];
            }
        }
    }
    
    private int[][] copy(int[][] theBoard)
    {
        int [][] copy = new int[theBoard.length][];
        for(int i = 0; i < theBoard.length; i++)
        {
            copy[i] = new int[theBoard[i].length];
            System.arraycopy(theBoard[i], 0, copy, 0, theBoard[i].length);
        }
        return copy;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        return new Board(copy(board));
    }
}
